import React, { useRef, useState } from 'react'
import './index.css'
import { handlerDate } from '../../utils/index'
import { Button, Image, message } from 'antd'
import { storage } from '../../utils/index'

const { getItem } = storage

function CommonList({ list, changeArticleStatus, getData, children }) {
  //权限
  const jurisdiction = useRef(getItem('jurisdiction'))

  // 记录滚动掉的高度
  const [scrollOffset, setScrollOffset] = useState(0)

  //ul的样式
  const itemSize = 100
  const ulStyle = {
    height: `${itemSize * list.length}px`,
    width: '100%'
  }

  //虚拟列表的每一项的计算
  // 容器存放9个li标签，一个li标签高度为100px
  const contentHeight = Math.min(9, list.length) * 100
  const getCurrentChilldren = () => {
    //顶部和底部缓存区缓存几个
    const itemCount = 8

    //96px
    const itemHeight = 100

    // 可视区起始索引
    const startIndex = Math.floor(scrollOffset / itemHeight)

    // 上缓冲区起始索引
    const firstIndex = Math.max(0, startIndex - itemCount)

    // 可视区能展示的元素的最大个数
    const numVisible = Math.min(9, list.length)

    // 下缓冲区结束索引
    const endIndex = Math.min(list.length, startIndex + numVisible + itemCount)

    const items = []
    for (let i = firstIndex; i < endIndex; i++) {
      const itemStyle = {
        position: 'absolute',
        // 计算每个元素在container中的top值
        top: `${100 * i}px`
      }

      const child = list[i]

      if (jurisdiction.current == 'adminUser') {
        items.push(
          <div
            key={child?.id}
            style={itemStyle}
            className="flex justify-around hover:bg-[#fafafa] cursor-pointer w-[100%]"
          >
            <div className="CommonList-item">{child?.id}</div>
            <div className="CommonList-item">{child?.title}</div>
            <div className="CommonList-item justify-center">
              {
                <Image
                  width={70}
                  height={70}
                  src={child?.articleImg}
                  fallback=""
                />
              }
            </div>
            <div className="CommonList-item">{handlerDate(child?.pubDate)}</div>
            <div className="CommonList-item">{child?.type}</div>
            <div className="CommonList-item">
              <Button type="primary" danger onClick={() => handlerDown(child.id)}>
                下架
              </Button>
            </div>
          </div>
        )
      } else {
        items.push(
          <div
            key={child?.id}
            style={itemStyle}
            className="flex justify-around hover:bg-[#fafafa] cursor-pointer w-[100%]"
          >
            <div className="CommonList-item">{child?.id}</div>
            <div className="CommonList-item">{child?.title}</div>
            <div className="CommonList-item justify-center">
              {
                <Image
                  width={70}
                  height={70}
                  src={child.articleImg}
                  fallback=""
                />
              }
            </div>
            <div className="CommonList-item">{handlerDate(child?.pubDate)}</div>
            <div className="CommonList-item">{child?.type}</div>
            <div className="CommonList-item">{child?.status == 1 ? '审核中' : '已发布'}</div>
          </div>
        )
      }
    }

    return items
  }

  // 当触发滚动就重新计算
  const handlerScroll = event => {
    const { scrollTop } = event.currentTarget
    setScrollOffset(scrollTop)
  }

  //管理员下架
  const handlerDown = async id => {
    try {
      let res = await changeArticleStatus({
        id,
        doneType: 1
      })
      //触发父组件更新
      getData()
    } catch (error) {
      message.error('异常')
      console.log('err', error)
    }
  }

  return (
    <>
      {children}
      {/* 管理员查看的列表 */}
      {/* 样式说明，容器存放9个li标签，一个li标签高度为100px/1.25rem */}
      <div
        className="overflow-auto relative"
        style={{ height: `${contentHeight}px` }}
        onScroll={handlerScroll}
      >
        {jurisdiction.current == 'adminUser' ? (
          <div className="flex flex-col" style={ulStyle}>
            {getCurrentChilldren()}
          </div>
        ) : (
          //普通用户
          <div className="flex flex-col" style={ulStyle}>
            {getCurrentChilldren()}
          </div>
        )}
      </div>
    </>
  )
}

export default CommonList
